package com.baixun.gascommon.handler;


import com.baixun.gascommon.enums.ResultStatus;
import com.baixun.gascommon.exception.CustomException;
import com.baixun.gascommon.exception.NoAuthorityFindException;
import com.baixun.gascommon.exception.NoUserIdException;
import com.baixun.gascommon.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 自定义全局异常处理器
 */

@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory
            .getLogger(GlobalExceptionHandler.class);


    /**
     * 权限为拥有处理
     * @param msg
     * @return
     */
    @ExceptionHandler(NoAuthorityFindException.class)
    public R NoAuthorityFindException(String msg){
        return R.fail(ResultStatus.NoAuthority);
    }


    // 处理自定义业务异常
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseEntity<Object> handleCustomException(CustomException ex) {
        return ResponseEntity.status(ex.getCode())
                .body(new ErrorResponse(ex.getMessage(), ex.getCode()));
    }

    // 处理参数验证异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseEntity<Object> handleValidationException(MethodArgumentNotValidException ex) {
        String errorMessage = ex.getBindingResult().getFieldError().getDefaultMessage();
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(new ErrorResponse(errorMessage, HttpStatus.BAD_REQUEST.value()));
    }

    // 处理其他未捕获的异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<Object> handleException(Exception ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(new ErrorResponse("服务器内部错误，请稍后重试", HttpStatus.INTERNAL_SERVER_ERROR.value()));
    }

    // 定义错误响应数据结构
    public static class ErrorResponse {
        private String message;
        private int status;

        public ErrorResponse(String message, int status) {
            this.message = message;
            this.status = status;
        }

        public String getMessage() {
            return message;
        }

        public int getStatus() {
            return status;
        }
    }
}
